package db;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

public class DatabaseConnection {
    private static DatabaseConnection instance;
    private static Connection connection;
    private boolean isClosed = false;

    private DatabaseConnection() {
        try {
            Class.forName("org.sqlite.JDBC");
            connection = DriverManager.getConnection("jdbc:sqlite:account.db");
            initializeDatabase();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static synchronized DatabaseConnection getInstance() {
        if (instance == null || instance.isClosed) {
            instance = new DatabaseConnection();
        }
        return instance;
    }

    public  Connection getConnection() {
        if (isClosed) {
            throw new IllegalStateException("Database connection is closed.");
        }
        return connection;
    }

    public void closeConnection() {
        if (connection != null && !isClosed) {
            try {
                connection.close();
                isClosed = true;
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
    private void initializeDatabase() throws SQLException {
        String createTableSQL = "CREATE TABLE IF NOT EXISTS transactions (" +
                "id INTEGER PRIMARY KEY AUTOINCREMENT," +
                "description TEXT NOT NULL," +
                "amount REAL NOT NULL," +
                "type TEXT NOT NULL)";
        try (java.sql.Statement statement = connection.createStatement()) {
            statement.execute(createTableSQL);
        }
    }
}